<?php
namespace app\common\util;

use app\admin\model\GlobalConfig;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
class MailUtil
{
    /**
     * 发送邮箱
     *
     * 使用方式
     * use app\common\util\Mail;
     * Mail::go('123@qq.com','这是来自一封信','你好！')
     *
     * @param array $data
     * @param string $addr 地址
     * @param string $title 标题
     * @param string $content 内容
     * @return mixed
     */
    public static function go($addresses, $title, $content, $files = [])
    {
        $mail = new PHPMailer(true);
        $data = GlobalConfig::getValues(['smtp_host', 'smtp_user', 'smtp_pass', 'smtp_ssl', 'smtp_port', 'smtp_title']);
        try {
            $mail->SMTPDebug = 0;
            $mail->CharSet = 'utf-8';
            $mail->isSMTP();
            $mail->Host = $data['smtp_host'];
            $mail->SMTPAuth = true;
            $mail->Username = $data['smtp_user'];
            $mail->Password = $data['smtp_pass'];
            $mail->SMTPSecure = $data['smtp_ssl'] ?: PHPMailer::ENCRYPTION_SMTPS;
            $mail->Port = $data['smtp_port'];
            $mail->setFrom($data['smtp_user'], $data['smtp_title'] ?? '膜一姐');
            $addresses = explode(',', $addresses);
            foreach ($addresses as $address) {
                $mail->addAddress($address);
            }
            if ($files) {
                foreach ($files as $file) {
                    $mail->addAttachment($file['file'], $file['file_name']);
                }
            }
            $mail->isHTML(true);
            $mail->Subject = $title;
            $mail->Body = $content;
            $mail->send();
            return ['code' => '200', 'msg' => '发送成功'];
        } catch (Exception $e) {
            return ['code' => '201', 'msg' => '发送失败' . $e->errorMessage()];
        }
    }
}